﻿using System;
using System.Runtime.InteropServices;

namespace BMproductions.Media.MediaPlayer.WMPPlus {
	public abstract class WMPSubMenu: IDisposable {
		public enum SubMenuPlace: int {
			Custom,
			BeginPos,
			EndPos,
			BeforeID,
			AfterID
		};

		private IntPtr native;

		public WMPMenu Owner { get; private set; }
		public abstract string Text { get; }
		public virtual SubMenuPlace MenuPlace { get { return SubMenuPlace.Custom; } }
		public virtual uint ID { get { return 0u; } }

		protected internal virtual void Invoke(IntPtr hMenu) { }
		protected internal virtual int Place(IntPtr hMenu) {
			return -1;
		}

		[DllImport(WMPPlusPublic.WMPPlusHookName, CharSet = CharSet.Auto, EntryPoint = "#503")]
		private static extern IntPtr CreateSubMenu(IntPtr menu,
			[MarshalAs(UnmanagedType.LPTStr)] string text,
			SubMenuPlace place,
			uint id);
		[DllImport(WMPPlusPublic.WMPPlusHookName, EntryPoint = "#504")]
		private static extern void DestroySubMenu(IntPtr item);

		public WMPSubMenu(WMPMenu owner) : this(owner, true) { }
		protected WMPSubMenu(WMPMenu owner, bool prepare) {
			Owner = owner;
			if (prepare)
				Init();
		}

		protected virtual void Init() {
			if (Owner != null) {
				this.native = CreateSubMenu(Owner.Native, Text, MenuPlace, ID);
				Owner.Menus.Add(this.native, this);
			}
		}

		public void Dispose() {
			if (this.native != IntPtr.Zero && Owner != null) {
				Owner.Menus.Remove(this.native);
				DestroySubMenu(this.native);
			}
			this.native = IntPtr.Zero;
		}
	}
}
